<?php
// +-------------------------------------------------------------------
// |
// +-------------------------------------------------------------------
// | Copyright (c) 2009-2016 All rights reserved.
// +-------------------------------------------------------------------
namespace Service\User;

class PointLog extends \Service\Common\BaseModel
{
    protected $name = 'point_log';

    const TYPE_GIVE = 0;//支付赠送
    const TYPE_DEVIATION = 1;//下单抵扣
    const TYPE_CANCEL = 2;//取消返还

    const TYPE_LABEL = [
        self::TYPE_GIVE => '支付赠送',
        self::TYPE_DEVIATION => '下单抵扣',
        self::TYPE_CANCEL => '取消返还',
    ];

    //积分列表
    public function pointList($uid, $page_num = 1, $page_size = 5)
    {
        $where = [
            'uid' => $uid,
        ];
        $list = (array)$this->where($where)->order('id desc')->page($page_num, $page_size)->select();
        foreach ($list as &$row) {
            $row['type_label'] = self::TYPE_LABEL[$row['type']];
        }
        $count = $this->where($where)->count();
        return [
            $list,
            $page_count = $count,
            $page_total = ceil($count / $page_size),
            $total_point = M('user')->where(['uid' => $uid])->getField('total_point')
        ];
    }

    //赠送积分
    public function addGivePoint($uid, $order_id, $goods_title, $point)
    {
        $this->_add($uid, $order_id, $goods_title, $point, self::TYPE_GIVE);
    }

    //抵扣积分
    public function addDeviationPoint($uid, $order_id, $goods_title, $point)
    {
        $this->_add($uid, $order_id, $goods_title, $point, self::TYPE_DEVIATION);
    }

    //取消订单
    public function addCancelPoint($uid, $order_id, $goods_title, $point)
    {
        $this->_add($uid, $order_id, $goods_title, $point, self::TYPE_CANCEL);
    }

    protected function _add($uid, $order_id, $goods_title, $point, $type)
    {
        if ($point == 0) {
            return;
        }

        //积分记录
        $insert_id = $this->add([
            'type' => $type,
            'uid' => $uid,
            'order_id' => $order_id,
            'goods_title' => $goods_title,
            'point' => $point,
            'create_time' => date('Y-m-d H:i:s')
        ]);
        if (!$insert_id) {
            throw new \Exception("积分记录插入失败");
        }

        //积分累计
        $point_str = $point > 0 ? "+$point" : $point;
        $update = M('user')->where([
            'uid' => $uid
        ])->save([
            'total_point' => ['exp', "total_point{$point_str}"],
            'update_time' => date('Y-m-d H:i:s')
        ]);
        if ($update === false) {
            throw new \Exception("积分累计失败");
        }
    }
}